<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.title')" v-model="listQuery.keyword" style="width: 200px;" class="filter-item"/>
      <el-select v-model="listQuery.classifyId" style="width: 140px" class="filter-item" placeholder="选择分类">
        <el-option v-for="item in classifyList" :key="item.id" :label="item.title" :value="item.id"/>
      </el-select>

      <el-select v-model="listQuery.is_sync" style="width: 100px" class="filter-item" placeholder="是否同步">
        <el-option label="不限" value=""/>
        <el-option label="不同步" value="no"/>
        <el-option label="同步" value="yes"/>
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getList(true)">{{ $t('table.search') }}</el-button>
      <el-button class="batch-delete" type="primary" @click="batchArticleDelete">删除选中</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column :label="$t('table.title')" prop="title" align="center"/>
      <el-table-column :label="$t('table.title')" prop="cover" align="center">
        <template slot-scope="scope">
          <img :src="`${prefixUrl}/${scope.row.cover}`" alt="" style="width: 50px;height: 50px">
        </template>
      </el-table-column>
      <el-table-column :formatter="classifyName" label="分类" prop="classify_id" align="center"/>
      <el-table-column :label="$t('table.author')" prop="author" align="center"/>
      <el-table-column label="公众号名称" prop="wechat_name" align="center"/>
      <el-table-column :formatter="dateFormat" label="抓去时间" prop="crawl_time" align="center"/>
      <el-table-column label="是否要同步" prop="is_sync" align="center">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.is_sync === 'no' ? false:true"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeSync(scope)"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" width="150px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="deleteArticle(scope.row)">删除</el-button>
          <router-link class="link" :to="{name:'ArticleEdit',params:{id:scope.row.id}}">编辑</router-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { fetchList, deleteArticleById, deleteBath, dataSync } from '@/api/article'
import { classifyList } from '@/api/classify'
import moment from 'moment'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

import Vue from 'vue'

export default {
  name: 'ArticleList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: '',
        classifyId: null,
        is_sync: ''
      },
      classifyList: [],
      classifyIsLoad: false,
      prefixUrl: process.env.BASE_API
    }
  },
  created() {
    this.initLoadData()
  },
  methods: {

    // 加载数据
    initLoadData(rest) {
      if (!this.classifyIsLoad) {
        this.getClassifyList(this.getList)
        this.classifyIsLoad = true
      } else {
        this.getList()
      }
    },

    // 加载列表数据
    getList(rest) {
      if (rest === true) {
        this.listQuery.page = 1
      }
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.count
        this.listLoading = false
      })
    },

    classifyName(row, column) {
      var data = row[column.property]
      if (data == undefined) {
        return ''
      }
      for (var i = 0; i < this.classifyList.length; i++) {
        var ele = this.classifyList[i]
        if (data == ele.id) {
          return ele.title
        }
      }
    },

    // 触发是否同步事件
    changeSync(scope) {
      var index = scope.$index
      var sync = scope.row.is_sync === 'no' ? 'yes' : 'no'
      Vue.set(this.list[index], 'is_sync', sync)
      dataSync({ id: scope.row.id })
    },

    // 分类列表
    getClassifyList(callFn) {
      classifyList().then(response => {
        this.classifyList = response.data.data
        console.info(this.classifyList)
        if (callFn && typeof callFn === 'function') {
          callFn()
        }
      })
    },

    // 时间格式化
    dateFormat: function(row, column) {
      var date = row[column.property]
      if (date == undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    // 获取列表
    classifyFormat(row, column) {
      var colData = row[column.property]
      if (colData == undefined) {
        return ''
      }
      for (var i in this.classifyList) {
        var data = this.classifyList[i]
        if (data.id == colData) {
          return data.title
        }
        break
      }
    },

    // 删除文章
    deleteArticle(data) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteArticleById({ id: data.id }).then(response => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          var self = this
          setTimeout(function() {
            self.getList()
          }, 1000)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 选中删除
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },

    // 批量删除
    batchArticleDelete() {
      var arr = ''
      for (var i in this.selectChangeData) {
        var ele = this.selectChangeData[i]
        arr += ',' + ele.id
      }

      if (arr) {
        arr = arr.substring(1)
      }

      this.$confirm('确定批量删除？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteBath({ ids: arr }).then(response => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          var self = this
          setTimeout(function() {
            self.getList()
          }, 1000)
        })
      }).catch(() => {})
    },

    handleSelectionChange(val) {
      this.selectChangeData = val
    },
    //编辑文章
    editArticle(data){

    }

  }
}

</script>

<style>

  .batch-delete{
    float: right;
  }

  .link{
    color: #409EFF;
  }

</style>
